using AutoMapper;
using MediatR;
using RBAC.Domain.SmartHealthcare.Hosiptial;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using SmartHealthcare.Read.Api.Application.Command.Payment;
using SmartHealthcare.Read.Api.DTo;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace SmartHealthcare.Read.Api.Application.Handler.Payment
{
    /// <summary>
    /// 获取支付记录详情处理器
    /// </summary>
    public class GetPaymentRecordDetailHandler : IRequestHandler<GetPaymentRecordDetailCommand, APIResult<PaymentRecordDto>>
    {
        private readonly IBaseRepository<PaymentRecordModel> paymentRepository;
        private readonly IMapper mapper;
        private readonly ILogger<GetPaymentRecordDetailHandler> logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="paymentRepository">支付记录仓储</param>
        /// <param name="mapper">对象映射器</param>
        /// <param name="logger">日志记录器</param>
        public GetPaymentRecordDetailHandler(
            IBaseRepository<PaymentRecordModel> paymentRepository,
            IMapper mapper,
            ILogger<GetPaymentRecordDetailHandler> logger)
        {
            this.paymentRepository = paymentRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        /// <summary>
        /// 处理获取支付记录详情请求
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>支付记录详情</returns>
        public Task<APIResult<PaymentRecordDto>> Handle(GetPaymentRecordDetailCommand request, CancellationToken cancellationToken)
        {
            APIResult<PaymentRecordDto> result = new APIResult<PaymentRecordDto>();

            try
            {
                logger.LogInformation($"开始查询支付记录详情，记录ID：{request.Id}");

                // 获取支付记录
                var record = paymentRepository.GetModel(request.Id);

                if (record == null || record.IsDeleted)
                {
                    logger.LogWarning($"支付记录不存在，ID：{request.Id}");
                    result.Code = APIEnums.Error;
                    result.Msg = "支付记录不存在";
                    return Task.FromResult(result);
                }

                // 转换为DTO
                var recordDto = mapper.Map<PaymentRecordDto>(record);

                logger.LogInformation($"查询成功，支付记录ID：{record.Id}，患者：{record.PatientName}，金额：{record.Amount}");

                result.Data = recordDto;
                result.Code = APIEnums.Success;
                result.Msg = "查询支付记录详情成功";
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"查询支付记录详情时发生异常，记录ID：{request.Id}");
                result.Code = APIEnums.Error;
                result.Msg = $"查询支付记录详情失败：{ex.Message}";
            }

            return Task.FromResult(result);
        }
    }
} 